<template>
    <a-modal title="同意" :visible.sync="show" width="650px" :confirm-loading="loading" @ok="handleConfirm" @cancel="handleCancel">
    <j-form-container>
      <a-form-model ref="formRef" :model="formValue" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="审批意见" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="comments">
             <!-- <a-textarea v-model="formValue.comments" placeholder="请输入审批意见" :auto-size="{ minRows: 4, maxRows: 5 }" /> -->
             <j-quill-mention v-model="formValue.comments" placeholder="请输入审批意见,可通过@并输入姓名提醒指定人员"></j-quill-mention>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24" v-if="processInfo.signFlag">
            <a-form-model-item label="签名画板" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signInfo">
             <vue-esign ref="esignRef" :width="800" :height="200" style="border: 1px solid #d9d9d9"/>
             <el-button v-if="!formValue.signInfo" size="mini" type="primary" @click="handleGenerate">生成图片</el-button>
             <el-button size="mini" type="warning" @click="handleReset">清空画板</el-button>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="24">
            <a-form-model-item label="图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="imageList">
              <j-image-upload v-model="formValue.imageList" :isMultiple = "true" @change="imgChange"></j-image-upload>
              <div class="el-upload__tip">添加图片 | 每张图不超过20MB</div>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fileList">
              <j-upload v-model="formValue.fileList" @change="fileChange"></j-upload>
              <div class="el-upload__tip">添加附件 | 单个附件不超过20MB</div>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="formValue.signInfo">
            <a-form-model-item label="签名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signInfo">
              <img :src="formValue.signInfo" style="max-width:150px; height: auto;">
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
   </a-modal>
</template>

<script>

  import {
    uploadAction,
    httpAction
  } from '@/api/manage'
  import JQuillMention from './JQuillMention'
  export default {
    name: "AgreeModal",
    components: { JQuillMention },
    props: {
      // 是否显示
      visible: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        loading: false,
        formValue: {
          comments: "",
          imageList:'',
          fileList:'',
        },
        imageList: [],  //图片列表
        fileList: [],  //文件列表
        show:false,
        processInfo:{},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        validatorRules:{
          // comments:[{ required:true,message:'请填写审批意见' }],
        },
        url:{
          agree:'workspace/agree'
        },
      };
    },
    // computed: {
    //   show: {
    //     get() {
    //       return this.visible;
    //     },
    //     set(visible) {
    //       this.$emit("update:visible", visible);
    //     },
    //   },
    // },
    methods: {
      //显示弹窗
      showModal(record,mobileSgnatureUrl){
        this.processInfo = record
        this.formValue = {
          comments: "",
          imageList:'',
          fileList:'',
          signInfo:''
        }
        this.imageList = []
        this.fileList = []
        this.formValue.signInfo = mobileSgnatureUrl
        this.show = true
      },
      handleReset() {
        //清空画布
        this.$refs.esignRef.reset();
        this.formValue.signInfo = "";
      },
      //签名校验
      validateSignInfo(rule, value, callback){
        if(this.processInfo.signFlag){
          if(value){
            callback()
          }else{
            callback("请设置签名")
          }
        }else{
          callback()
        }
      },
      handleGenerate() {
        this.$refs.esignRef
          .generate()
          .then((res) => {
            // 得到了签字生成的base64图片
            const file = this.base64ToFile(res)
            this.uploadHandle(file)
          })
          .catch(() => {
            //  没有签名，点击生成图片时调用
            this.$message("未签名！");
          });
      },
      //签名上传
      uploadHandle(file) {
        let formData = new FormData()
        formData.append('file', file)
        uploadAction(window._CONFIG['domianURL'] + '/file/upload', formData).then((res) => {
          if (res.success) {
            this.formValue.signInfo = res.message
            this.$message.success('生成成功')
          }else{
            this.$message.error('签名失败！')
          }
        })
        .finally(()=>{
          this.$refs['formRef'].clearValidate(['signInfo'])   
        })
      },
      // base64转file
       base64ToFile(data) {
          // 将base64 的图片转换成file对象上传 atob将ascii码解析成binary数据
          let binary = atob(data.split(',')[1]);
          let mime = data.split(',')[0].match(/:(.*?);/)[1];
          let array = [];
          for (let i = 0; i < binary.length; i++) {
              array.push(binary.charCodeAt(i));
          }
          let fileData = new Blob([new Uint8Array(array)], {
              type: mime,
          });
          let file = new File([fileData], `${new Date().getTime()}.png`, {
              type: mime
          });
          return file;
      },
      //上传图片
      imgChange(value){
        this.imageList=[]
        if(value){
          let list = value.split(',')
          list.map((item)=>{
            let lastOf = item.lastIndexOf('/') // '/'所在的最后位置
            const name = item.substr(lastOf + 1) //截取文件名称和后缀
            this.imageList.push({name:name, url:item,type:'image'})
          })
        }else{
          this.imageList = []
        }
      },
      //上传文件
      fileChange(value){
        this.fileList=[]
        if(value){
          let list = value.split(',')
          list.map((file)=>{
            let lastOf = file.lastIndexOf('/') // '/'所在的最后位置
            const name = file.substr(lastOf + 1) //截取文件名称和后缀
            this.fileList.push({name:name, url:file,type:'file'})
          })
        }else{
          this.fileList = []
        }
      },
      // 确认操作
      handleConfirm() {
        this.$refs.formRef.validate((valid) => {
          if (!valid) return;
          const {
            imageList,
            fileList,
            ...restParams
          } = this.formValue;
         restParams.taskId = this.processInfo.taskId
         restParams.processInstanceId = this.processInfo.processInstanceId
         restParams.attachments=[...this.imageList, ...this.fileList]
          this.loading = true;
          httpAction(this.url.agree,restParams,'post')
            .then((res)=>{
              if(res.success){
                this.$message.success(res.message)
                this.handleCancel()
                this.$emit("ok",'agree')
              }else{
                this.$message.warning(res.message)
              }
            })
            .finally(()=>{
              this.loading = false;
            })
        });
      },
      // 取消操作
      handleCancel() {
        this.$refs.formRef.resetFields();
        this.formValue = {
          comments: "",
          imageList: [],
          fileList: [],
        };
        this.show = false;
      },
    },
  };
</script>
<style lang="less" scoped>
  .el-upload__tip {
    font-size: 12px;
    color: #606266;
  }

  /deep/.ant-upload.ant-upload-select-picture-card {
    margin-bottom: 0;
  }
</style>